<?php

namespace common\models\c2\entity;

use Yii;
use yii\helpers\ArrayHelper;
use yii\validators\RequiredValidator;

/**
 * This is the model class for table "{{%product_combination}}".
 *
 * @property string $id
 * @property string $product_id
 * @property string $name
 * @property string $label
 * @property string $stock
 * @property string $memo
 * @property integer $status
 * @property integer $position
 * @property string $created_at
 * @property string $updated_at
 */
class ProductCombination extends \cza\base\models\ActiveRecord
{

    use \common\traits\AttachmentTrait;

    public $items;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%product_combination}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['product_id', 'position', 'stock'], 'integer'],
            [['memo'], 'string'],
            [['created_at', 'updated_at', 'items'], 'safe'],
            [['items'], 'validateItems'],
            [['name', 'label'], 'string', 'max' => 255],
            [['status'], 'integer', 'max' => 4],
        ];
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'attachmentsBehavior' => [
                'class' => \cza\base\modules\Attachments\behaviors\AttachmentBehavior::className(),
                'attributesDefinition' => [
                    'avatar' => [
                        'class' => \common\models\c2\entity\EntityAttachmentImage::className(),
                        'validator' => 'image',
                        'rules' => [
                            'maxFiles' => 1,
                            'uploadRequired' => Yii::t('app.c2', 'Photo must upload.'),
                            // 'skipOnEmpty' => false,
                            // 'skipOnError' => false,
                            'extensions' => Yii::$app->params['config']['upload']['imageWhiteExts'],
                            // 'extensions' => ['jpg'],
                            'maxSize' => Yii::$app->params['config']['upload']['maxFileSize'],
                            // 'maxSize' => '2048',
                        ]
                    ]
                ]
            ],
        ]);
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app.c2', 'ID'),
            'product_id' => Yii::t('app.c2', 'Product ID'),
            'product_name' => Yii::t('app.c2', 'Product'),
            'name' => Yii::t('app.c2', 'Name'),
            'label' => Yii::t('app.c2', 'Label'),
            'memo' => Yii::t('app.c2', 'Memo'),
            'status' => Yii::t('app.c2', 'Status'),
            'position' => Yii::t('app.c2', 'Position'),
            'created_at' => Yii::t('app.c2', 'Created At'),
            'updated_at' => Yii::t('app.c2', 'Updated At'),
            'stock' => Yii::t('app.c2', 'Stock'),
        ];
    }

    public function validateItems($attribute)
    {
        $items = $this->$attribute;

        foreach ($items as $index => $row) {
            $requiredValidator = new RequiredValidator();
            $error = null;
            $requiredValidator->validate($row['product_id'], $error);
            if (!empty($error)) {
                $key = $attribute . '[' . $index . '][product_id]';
                $this->addError($key, $error);
            }
        }
    }

    /**
     * @inheritdoc
     * @return \common\models\c2\query\ProductCombinationQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \common\models\c2\query\ProductCombinationQuery(get_called_class());
    }

    /**
     * setup default values
     **/
    public function loadDefaultValues($skipIfSet = true)
    {
        parent::loadDefaultValues($skipIfSet);
    }

    public function getCombinationItems()
    {
        return $this->hasMany(ProductCombinationItem::className(), ['combination_id' => 'id']);
    }

    public function loadItems()
    {
        $this->items = $this->getCombinationItems()->all();
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub
        if (!empty($this->items)) {
            foreach ($this->items as $item) {
                $attributes = [
                    'label' => isset($item['label']) ? $item['label'] : '',
                    'product_id' => isset($item['product_id']) ? $item['product_id'] : 0,
                    'need_number' => isset($item['need_number']) ? $item['need_number'] : 0,
                    'position' => isset($item['position']) ? $item['position'] : 0,
                ];
                if (isset($item['id']) && $item['id'] == '') {
                    $itemModel = new ProductCombinationItem();
                    $itemModel->setAttributes($attributes);
                    $itemModel->link('owner', $this);
                } elseif (isset($item['id'])) {
                    $itemModel = ProductCombinationItem::findOne($item['id']);
                    if (!is_null($itemModel)) {
                        $itemModel->updateAttributes($attributes);
                    }
                }
            }
        }
        if (isset($changedAttributes['stock'])) {
            $product = $this->product;
            $combs = $product->combinations;
            $sum = 0;
            foreach ($combs as $comb) {
                $sum += $comb->stock;
            }
            $product->updateAttributes(['stock' => $sum]);
        }
    }

    public function beforeDelete()
    {
        foreach ($this->getCombinationItems()->all() as $item) {
            $item->delete();
        }
        return parent::beforeDelete(); // TODO: Change the autogenerated stub
    }

    public function getProduct()
    {
        return $this->hasOne(Product::className(), ['id' => 'product_id']);
    }

}
